package com.cyanite.playlv2api.parsers.json;

import com.cyanite.playlv2api.types.Email;
import com.cyanite.playlv2api.types.FriendInvitesResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class FriendInvitesResultParser extends AbstractParser<FriendInvitesResult> {
    
    @SuppressWarnings("unchecked")
    @Override
    public FriendInvitesResult parse(JSONObject json) throws JSONException {
        
        FriendInvitesResult obj = new FriendInvitesResult();
        if (json.has("users")) {
            obj.setContactsOnPlayLv2(
                new GroupParser(
                    new UserParser()).parse(json.getJSONArray("users")));
        } 
        if (json.has("emails")) {
            Email emails = new Email();
            if (json.optJSONObject("emails") != null) {
                JSONObject emailsAsObject = json.getJSONObject("emails");
                emails.add(emailsAsObject.getString("email"));
            } else if (json.optJSONArray("emails") != null) {
                JSONArray emailsAsArray = json.getJSONArray("emails");
                for (int i = 0; i < emailsAsArray.length(); i++) {
                    emails.add(emailsAsArray.getString(i));
                }
            }
            obj.setContactEmailsOnNotOnPlayLv2(emails);
        }
        if (json.has("invited")) {
            Email emails = new Email();
            JSONArray array = json.getJSONArray("invited");
            for (int i = 0; i < array.length(); i++) {
                emails.add(array.getString(i));
            }
            obj.setContactEmailsOnNotOnPlayLv2AlreadyInvited(emails);
        }
        return obj;
    }
}